package org.xtext.runtime.plan;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.xtext.runtime.eis.EISService;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.term.ITerm;
import org.xtext.runtime.term.Variable;
import org.xtext.runtime.util.Bindings;
import eis.exceptions.ManagementException;
import eis.iilang.Parameter;

public class EISSetupStep implements IPlanStep {
	private ITerm id, jar;
	private EISService service;
	
	public EISSetupStep(ITerm id, ITerm jar) {
		this.id = id;
		this.jar = jar;
	}
	
	public EISSetupStep(ITerm id) {
		this.id = id;
	}
	
	@Override
	public EISSetupStep apply(Bindings set) {
		return new EISSetupStep(id.apply(set), (jar == null) ? null : jar.apply(set));
	}

	@Override
	public void handle(Agent agent, PlanStack planStack) {
		if (jar == null) {
			agent.eisService(EISService.getService((String) Variable.rawValue(id).value()));
		} else {
			service = EISService.getService((String) Variable.rawValue(id).value(), (String) Variable.rawValue(jar).value());
			
			if (service.getEnvironmentState().equals("initializing")) {
				try {
					service.eisInit(new HashMap<String, Parameter>());
					agent.eisService(service);
				} catch (ManagementException e) {
					e.printStackTrace();
					agent.logAction(toString("") + " [FAILED TO LAUNCH JAR]");
					planStack.fail();
					return;
				}
			}
		}
		agent.logAction(toString("") + " [SUCCESS]");
	}

	@Override
	public String toString(String tabs) {
		String output = tabs + "eis_setup(" + id;
		if (jar != null) output += "," + jar;
		return output + ")";
	}
	
	public String toFullString(String tabs) {
		return toString(tabs);
	}
	
	@Override
	public Set<Variable> variables() {
		HashSet<Variable> set = new HashSet<Variable>();
		if (id instanceof Variable) set.add((Variable) id);
		if (jar instanceof Variable) set.add((Variable) jar);
		return set;
	}

	@Override
	public IPlanStep copy(Map<String, Variable> vars) {
		ITerm i = id;
		ITerm j = jar;
		if (i instanceof Variable) i = vars.get(((Variable) id).identifier());
		if (j instanceof Variable) j = vars.get(((Variable) jar).identifier());
		return new EISSetupStep(i,j);
	}

	@Override
	public void reset() {
	}
}
